package com.gqr.threadsafe;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:DeadThreadError
 * author:guqingrong
 * Date:2024-04-27 10:19
 * Description:第二种线程安全问题: 死锁
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class DeadThreadError implements Runnable{
    int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        DeadThreadError r1 = new DeadThreadError();
        DeadThreadError r2 = new DeadThreadError();
        r1.flag=1;
        r2.flag=0;
        new Thread(r1).start();
        new Thread(r2).start();
    }
    @Override
    public void run() {
        System.out.println("flag = "+flag);
        if(flag==1){
            synchronized (o1){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (o2){
                    System.out.println("1");
                }
            }
        }
        else if(flag==0){
            synchronized (o2){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                synchronized (o1){
                    System.out.println("0");
                }
            }
        }
    }
}
